//
//  gameScreen.m
//  sheep-must-die
//
//  Created by eewert on 11/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "Math.h"
#import "gameScreen.h"




@implementation gameScreen

@synthesize sheepView;
@synthesize sheepRocketOnView;
@synthesize sheepImageArray;
@synthesize sheepRocketOnViewArray;
@synthesize coinView;
@synthesize coinImageArray;
@synthesize scoreLabel;
@synthesize score;

//@synthesize lineDrawView;
@synthesize runTimer;
@synthesize timerLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        runTimer = [[NSTimer scheduledTimerWithTimeInterval:(1.0/TIMER_FRAMES_PER_SECOND) target:self selector:@selector(timerFireMethod:) userInfo:runTimer repeats:YES] retain];
        scoreLabel.text = @"Score: 0";
    }
    return self;
}

- (void)dealloc
{
    [timerLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(CGRect)randCGRect
{
    float x = SCREEN_BORDER_WEST + arc4random() % (int)(SCREEN_WIDTH-SCREEN_BORDER_WEST-SCREEN_BORDER_EAST);
    //float y = 0 + arc4random() % ((int)(SCREEN_HEIGHT-SCREEN_BORDER_SOUTH) / 2);
    float y = 0 + arc4random() % ((int)(SCREEN_HEIGHT-SCREEN_BORDER_SOUTH));
    float w = 50*COIN_SIZE;
    float h = 50*COIN_SIZE;
    
    CGRect rect = CGRectMake(x, y, w, h);
    return rect;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    coinView = [[UIImageView alloc] initWithFrame: [self randCGRect]];
    coinImageArray = [NSArray arrayWithObjects:
                      [UIImage imageNamed:@"Coin1"],
                      [UIImage imageNamed:@"Coin1"],
                      [UIImage imageNamed:@"Coin2"],
                      [UIImage imageNamed:@"Coin3"],
                      [UIImage imageNamed:@"Coin4"],
                      [UIImage imageNamed:@"Coin5"],
                      [UIImage imageNamed:@"Coin5"],
                      [UIImage imageNamed:@"Coin4"],
                      [UIImage imageNamed:@"Coin3"],
                      [UIImage imageNamed:@"Coin2"],
                      nil];
    coinView.animationImages = coinImageArray;
    coinView.animationDuration = 0.75;
    coinView.animationRepeatCount = 0;
    [self.view addSubview:coinView];
    [coinView startAnimating];
    
    /*sheepRocketOnView = [[UIImageView alloc] initWithFrame: CGRectMake(SCREEN_BORDER_WEST + 50, SCREEN_HEIGHT-SCREEN_BORDER_SOUTH, 50*SHEEP_SIZE, 33*SHEEP_SIZE)];*/
    sheepRocketOnViewArray = [NSArray arrayWithObjects:
                       [UIImage imageNamed:@"SheepEyes"]
                       , nil];
    /*
    sheepRocketOnView.animationImages = sheepRocketOnViewArray;
    sheepRocketOnView.animationDuration = 3.0;
    sheepRocketOnView.animationRepeatCount = 1;
    [self.view addSubview:sheepRocketOnView];
    [sheepRocketOnView startAnimating];*/
    
    sheepView = [[UIImageView alloc] initWithFrame: CGRectMake(SCREEN_BORDER_WEST + 50, SCREEN_HEIGHT-SCREEN_BORDER_SOUTH, 50*SHEEP_SIZE, 33*SHEEP_SIZE)];
 /*   sheepImageArray = [NSArray arrayWithObjects:
                  [UIImage imageNamed:@"sheep_no_flame.png"]
                       , nil];
    sheepView.animationImages = sheepImageArray;
    sheepView.animationDuration = 1.0;
    sheepView.animationRepeatCount = 0;*/
    [self.view addSubview:sheepView];

    sheepView.image = [UIImage imageNamed:@"Sheep"];
    //    [sheepView startAnimating];
    
    
    
}

- (void)viewDidUnload
{
    [self setTimerLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchStart = [touch locationInView:[self view]];
    
    //lineDrawView.touchStart = touchStart;
    //lineDrawView.shouldDrawLine = NO;
    //[lineDrawView setNeedsDisplay];
    
    // Stop the sheep
    //sheepVelocity.x = 0;
    //sheepVelocity.y = 0;
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchEnd = [touch locationInView:[self view]];
    // TODO : Calculate magnitude and angle
    
    //lineDrawView.shouldDrawLine = NO;
    //[lineDrawView setNeedsDisplay];
    
    // line has been removed, now launch sheep
    sheepVelocity = CGPointMake((touchEnd.x - touchStart.x)*VEL_THROW,
                               (touchEnd.y - touchStart.y)*VEL_THROW);
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchEnd = [touch locationInView:[self view]];
    // uiview class method override (redraw)
    // TODO : Draw Line (magnitude and angle)
    
    //lineDrawView.touchEnd = touchEnd;
    //lineDrawView.shouldDrawLine = YES;
    //lineDrawView.shouldDrawLine = NO;
    //[lineDrawView setNeedsDisplay];
}

-(float)sheepCoinDistFromPoint:(CGPoint)a toPoint:(CGPoint)b
{
    float xDiff = (a.x+30) - b.x;
    float yDiff = (a.y+10) - b.y;
    return sqrtf(xDiff*xDiff + yDiff*yDiff);
}

-(void)updateScoreLabel{
    self.scoreLabel.text = [NSString stringWithFormat:@"Score: %d",self.score];
}

-(CGPoint)randPoint{
    
    
    int x = abs(SCREEN_BORDER_WEST) + arc4random() % (int)(SCREEN_WIDTH - SCREEN_BORDER_WEST - SCREEN_BORDER_EAST);
  
    int y = (50*COIN_SIZE) + arc4random() % ((int)(SCREEN_HEIGHT - SCREEN_BORDER_SOUTH - 100));
        
    
    
    return CGPointMake(x,y);
    
}

-(void)resetCoinPosition{
    
    CGPoint newLoc = [self randPoint];
    while([self sheepCoinDistFromPoint:coinView.center toPoint:newLoc] < COIN_RESET_DIST)
    {
        newLoc = [self randPoint];
    }
    
    coinResetTimer = 0;
        
    [coinView setCenter:newLoc]; 
}

-(void)coinCheck
{
    
    
    
    if ([self sheepCoinDistFromPoint:sheepView.frame.origin toPoint:coinView.frame.origin] <= 42)
    {
        self.score += (int)((float)POINTS_GAINED_FOR_TOUCHING_A_COIN * ((float)((TIMER_FRAMES_PER_SECOND *  SECONDS_COIN_LASTS_ON_SCREEN) - coinResetTimer) / (float)(TIMER_FRAMES_PER_SECOND *  SECONDS_COIN_LASTS_ON_SCREEN)));
        [self updateScoreLabel];
        [self resetCoinPosition];
    }
    
    if(coinResetTimer > SECONDS_COIN_LASTS_ON_SCREEN * TIMER_FRAMES_PER_SECOND){
        
        [self resetCoinPosition];
        
    }
    
    coinResetTimer++;
    
    
    float coinAlpha = 1.0f;
    
    if(coinResetTimer > (SECONDS_COIN_LASTS_ON_SCREEN * TIMER_FRAMES_PER_SECOND) * PERCENT_OF_DURATION_AT_WHICH_COIN_FADEOUT_BEGINS){
        
        coinAlpha = 1.0f + PERCENT_OF_DURATION_AT_WHICH_COIN_FADEOUT_BEGINS - ((float)coinResetTimer/((float)(SECONDS_COIN_LASTS_ON_SCREEN * TIMER_FRAMES_PER_SECOND)));
        
    }
    coinView.alpha = coinAlpha;
    
    
    
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    [self alertViewCancel:nil];
}

-(void)alertViewCancel:(UIAlertView *)alertView{    
    timeToQuit = YES;
}

- (void)timerFireMethod:(NSTimer*)theTimer
{
    
    count++;
    
    
    if(count == TIMER_FRAMES_PER_SECOND * GAME_PLAY_SECONDS){
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Game Over" message:[NSString stringWithFormat:@"You scored %d",score] delegate:self cancelButtonTitle:@"Main Menu" otherButtonTitles:nil];
        [alert show];
        [alert release];
        
        
    }
    
    
    if(timeToQuit){
        [self dismissModalViewControllerAnimated:YES];
        timeToQuit = NO;
    }
    
    if(count > TIMER_FRAMES_PER_SECOND * GAME_PLAY_SECONDS){
        
        return;
              
        
    }
    
    timerLabel.text = [NSString stringWithFormat:@"0:%02d",GAME_PLAY_SECONDS - (count / TIMER_FRAMES_PER_SECOND)];
    
    
    CGPoint curPos = sheepView.frame.origin;
    [self coinCheck];
    
    
    if(sheepVelocity.y> 50){
        [sheepView setImage:[UIImage imageNamed:@"SheepEyes"]]; // eyes
    }else{
        if(sheepVelocity.y < -10)
            [sheepView setImage:[UIImage imageNamed:@"SheepFlame"]]; // flames
        else
            [sheepView setImage:[UIImage imageNamed:@"Sheep"]]; // boring
    }
        
    // Gravity
    sheepVelocity.y += VEL_GRAVITY;
    
    // Friction
    if(curPos.y > SCREEN_HEIGHT - SCREEN_BORDER_SOUTH * SCREEN_GROUND_SIZE)
    {
        sheepVelocity.y -= VEL_GRAVITY * 0.75;
        //float avgFric = (2*VEL_FRICTION_AIR + VEL_FRICTION_GROUND) / 3;
        sheepVelocity.x *= (1-VEL_FRICTION_GROUND);
        sheepVelocity.y *= (1-VEL_FRICTION_GROUND);
    }
    else
    {
        sheepVelocity.x *= (1-VEL_FRICTION_AIR);
        sheepVelocity.y *= (1-VEL_FRICTION_AIR);
    }

    //float angle = atanf(sheepVelocity.y / sheepVelocity.x);
    
    // Border collision detect
    if(curPos.x < 0 + SCREEN_BORDER_WEST)
    {
        sheepVelocity.x = abs(sheepVelocity.x);
    }
    else if(curPos.x > SCREEN_WIDTH - SCREEN_BORDER_EAST)
    {
        sheepVelocity.x = -abs(sheepVelocity.x);
    }
    if(curPos.y < 0 + SCREEN_BORDER_NORTH)
    {
        sheepVelocity.y = abs(sheepVelocity.y);
    }
    else if(curPos.y > SCREEN_HEIGHT - SCREEN_BORDER_SOUTH)
    {
        self.score -= POINTS_LOST_FOR_TOUCHING_THE_GROUND;
        if(self.score < MINIMUM_NUMBER_OF_POINTS_POSSIBLE)
            self.score = MINIMUM_NUMBER_OF_POINTS_POSSIBLE;
        
        [self updateScoreLabel];
        sheepVelocity.y = -abs(sheepVelocity.y);
    }    
    
    // move by velocity
    CGFloat newX = curPos.x + sheepVelocity.x * VEL_SCALE;
    CGFloat newY = curPos.y + sheepVelocity.y * VEL_SCALE;
    CGFloat width = sheepView.frame.size.width;
    CGFloat height = sheepView.frame.size.height;
    CGRect newFrame = CGRectMake(newX, newY, width, height);
    
    [sheepView setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
    if (sheepVelocity.x < 0) {
        [sheepView setTransform:CGAffineTransformMake(-1, 0, 0, 1, 0, 0)];
    }   
    
    [sheepView setFrame:newFrame];
}

@end
